const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3001;

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'build')));

// Proxy endpoint for Aliyun DashScope API
app.post('/api/aliyun/video-generation', async (req, res) => {
  try {
    const { apiToken, model, prompt, style, size, fps, duration, photos } = req.body;
    
    if (!apiToken) {
      return res.status(400).json({ error: 'API token is required' });
    }
    
    // 获取图片URL（如果有）
    let imgUrl = null;
    if (photos && photos.length > 0 && photos[0].url) {
      imgUrl = photos[0].url;
      // 验证URL格式
      if (!imgUrl.startsWith('http://') && !imgUrl.startsWith('https://')) {
        console.log(`无效的图片URL格式: ${imgUrl}`);
        imgUrl = null;
      }
    }
    
    let apiUrl, requestBody;
    
    if (imgUrl) {
      // 图片转视频 - 使用正确的API端点
      apiUrl = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/video-generation/video-generation';
      requestBody = {
        model: 'wan2.5-i2v-preview',
        input: {
          prompt: prompt,
          img_url: imgUrl
        }
      };
    } else {
      // 文本生成视频 - 使用正确的API端点
      apiUrl = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/video-generation/video-generation';
      requestBody = {
        model: model || 'wanx-v1',
        input: {
          prompt: prompt,
          style: style || '<auto>',
          size: size || '1280*720'
        },
        parameters: {
          fps: fps || 24,
          duration: duration || 10
        }
      };
    }
    
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiToken}`,
        'X-DashScope-SSE': 'disable'
      },
      body: JSON.stringify(requestBody)
    });
    
    const data = await response.json();
    
    if (!response.ok) {
      console.error('Aliyun API error:', data);
      return res.status(response.status).json(data);
    }
    
    res.json(data);
  } catch (error) {
    console.error('Error proxying to Aliyun API:', error);
    res.status(500).json({ error: 'Failed to connect to Aliyun API' });
  }
});

// Proxy endpoint for checking Aliyun task status
app.get('/api/aliyun/task-status/:taskId', async (req, res) => {
  try {
    const { taskId } = req.params;
    const { apiToken } = req.query;
    
    if (!apiToken) {
      return res.status(400).json({ error: 'API token is required' });
    }
    
    const response = await fetch(`https://dashscope.aliyuncs.com/api/v1/tasks/${taskId}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${apiToken}`,
        'Content-Type': 'application/json'
      }
    });
    
    const data = await response.json();
    
    if (!response.ok) {
      return res.status(response.status).json(data);
    }
    
    res.json(data);
  } catch (error) {
    console.error('Error checking Aliyun task status:', error);
    res.status(500).json({ error: 'Failed to check task status' });
  }
});

// Fallback endpoint for simulated video generation
app.post('/api/simulate-video-generation', (req, res) => {
  const { photos, options } = req.body;
  
  // Simulate processing time
  setTimeout(() => {
    const videoId = `video_${Date.now()}`;
    res.json({
      success: true,
      taskId: videoId,
      videoUrl: 'https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4',
      thumbnail: photos[0]?.thumbnail || 'https://picsum.photos/seed/video/300/200.jpg',
      duration: options.duration || 10,
      size: `${Math.floor(Math.random() * 50) + 10}MB`,
      createdAt: new Date().toISOString()
    });
  }, 2000 + Math.random() * 3000);
});

// Serve the React app for any other requests
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});